package com.yiman.framework.shiro.realm;

import com.yiman.framework.shiro.service.LoginService;
import com.yiman.project.system.model.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

@Slf4j
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private LoginService loginService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) {
        log.info("进行用户认证....");
        UsernamePasswordToken upToken = (UsernamePasswordToken) authenticationToken;
        String username = upToken.getUsername();
        log.info("从upToken中获取的username:"+username);
        String password = "";
        if (upToken.getPassword() != null) {
            password = new String(upToken.getPassword());
            log.info("从upToken中获取的password:{}和{}",password,getName());
        }
        User user = null;
        try {
            //查数据库
//            user.setUserId(33);
//            user.setUserName("123");
//            user.setPassword("");
            user = loginService.login(username, password);
        } catch (Exception e) {
            log.info("对用户[" + username + "]进行登录验证..验证未通过{}", e.getMessage());
            throw new AuthenticationException(e.getMessage(), e);
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, user.getLoginName());
        return info;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        return null;
    }
}
